package com.dex4d.core.http.converter;

import com.dex4d.core.http.ApiException;
import com.dex4d.model.HttpResult;
import com.dex4d.utils.GsonUtil;
import com.dex4d.utils.LogUtils;
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;

import java.io.IOException;

import okhttp3.ResponseBody;
import retrofit2.Converter;

/**
 * Created by chengyuchun on 2017/4/6.
 */
final class CustomGsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
    private final Gson gson;
    private final TypeAdapter<T> adapter;

    CustomGsonResponseBodyConverter(Gson gson, TypeAdapter<T> adapter) {
        this.gson = gson;
        this.adapter = adapter;
    }

    @Override
    public T convert(ResponseBody value) throws IOException {
        JsonReader jsonReader = gson.newJsonReader(value.charStream());
        try {
            T t = adapter.read(jsonReader);
            if (t != null) {
                if (t instanceof HttpResult){
                    HttpResult result = (HttpResult) t;
                    //根据实际业务情况抛出异常
                    if (result.getError() != null) {
                        throw new ApiException(result.getError().getCode(), result.getError().getMessage());
                    }
                }
            }

            LogUtils.json(GsonUtil.toJsonString(t));
            return t;

        } finally {
            value.close();
        }
    }
}
